package com.hexus.eve.actions;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.ReflectionSaltSource;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import com.hexus.eve.application.Constants;
import com.hexus.eve.entities.security.SecurityGroup;
import com.hexus.eve.entities.security.User;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class Register extends ActionSupport{
	@Autowired
	private SessionFactory sessionFactory;
	@Autowired
	private Constants constants;
	@Autowired
	private ShaPasswordEncoder shaEncoder;
	@Autowired
	private ReflectionSaltSource saltSource;
	@Autowired
	private AuthenticationManager authenticationManager;
	
	private String name;
	private String password;
	private String email;
	
	@Override
	public String execute() throws Exception {
		HibernateTemplate ht = new HibernateTemplate(sessionFactory);
		User user = new User();
		user.setName(name);
		user.setPassword(shaEncoder.encodePassword(password, saltSource.getSalt(user)));
		user.setEmail(email);
		user.setEnabled(true);
		
		String defaultGroupsList = constants.getProperty(Constants.PropertyNames.DEFAULT_GROUPS);
		if(defaultGroupsList != null) {
			String[] defaultGroupIds = defaultGroupsList.split(";");
			List<SecurityGroup> defaultGroups = new ArrayList<SecurityGroup>();
			int id;
			for(int i = 0; i < defaultGroupIds.length; i++) {
				try {
					id = Integer.parseInt(defaultGroupIds[i]);
				} catch (NumberFormatException e) { 
					continue;
				}
				
				SecurityGroup sg = ht.get(SecurityGroup.class, id);
				if(sg != null)
					defaultGroups.add(sg);
			}
			if(defaultGroups.size() > 0)
				user.setGroups(defaultGroups);
		}
		
		ht.save(user);
		
		//Authenticate user
	    Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(name, password));
	    SecurityContextHolder.getContext().setAuthentication(authentication);
	    
		return SUCCESS;		
	}
	
	@Override
	public void validate() {
		HibernateTemplate ht = new HibernateTemplate(sessionFactory);
		User user = ht.get(User.class, name);
		if(user != null) {
			ResourceBundle bundle = ResourceBundle.getBundle ("global", getLocale());
			addFieldError("name", bundle.getString("validation.user.exists"));
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	
	
}
